<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >

  
  <div style="height: 50px;">
    <el-button @click="openDialog" :disabled="props.isDisabled">批量新增</el-button>
    <el-button @click="handleAdd" :disabled="props.isDisabled">新增明细</el-button>
    <InventoryForm ref="formRefAdd" :pomainId="props.pomainId" @success="handleSuccess" />
    <InventoryForm2 ref="formRefAdd2" :pomainId="props.pomainId" @success2="handleSuccess2" />

  </div>

    <el-table :data="formData" class="-mt-10px"  style="height: 290px;" border>
      <el-table-column label="序号" type="index"  width="100" />




      <el-table-column label="存货编码" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryCode`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryCode" placeholder="请输入存货编码"  @click="openDialog2($index)"   :disabled="props.isDisabled" />
          </el-form-item>
        </template>
      </el-table-column>





      
      <el-table-column label="存货名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryName" placeholder="请选择存货名称"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="规格型号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventorySpecModel`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventorySpecModel" placeholder="请输入规格型号"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryUnitName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryUnitName" placeholder="请输入单位"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>


      <el-table-column label="货位号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.cposcode`" :rules="formRules.required" class="mb-0px!">
            <el-select v-model="row.locationName" placeholder="请选择货位号" :disabled="props.isDisabled" :loading="selectLoading"  filterable remote   @change="handleLocationChange($event, row)" :remote-method="remoteLocation">
              <el-option
                v-for="item in locationList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>          
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.qty`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.qty" placeholder="请输入数量" :disabled="props.isDisabled" @input="calculateValues($index)"/>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="已使用数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.useQty`"  class="mb-0px!">
            <el-input v-model="row.useQty" placeholder="已使用数量" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="总数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.sumQty`"  class="mb-0px!">
            <el-input v-model="row.sumQty" placeholder="总数量" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="税率" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.irate`"  class="mb-0px!">
            <el-input v-model="row.irate" placeholder="请输入税率" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单价" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.price`"  class="mb-0px!">
            <el-input v-model="row.price" placeholder="请输入单价" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="含税单价" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.itaxprice`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.itaxprice" placeholder="请输入含税单价" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="金额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.imoney`"  class="mb-0px!">
            <el-input v-model="row.imoney" placeholder="请输入金额" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="税额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.itax`"  class="mb-0px!">
            <el-input v-model="row.itax" placeholder="请输入税额" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="价税合计" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.isum`"  class="mb-0px!">
            <el-input v-model="row.isum" placeholder="请输入价税合计" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>




      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.cbmemo`" class="mb-0px!">
            <el-input v-model="row.cbmemo" placeholder="请输入备注" :disabled="props.isDisabled"/>
          </el-form-item>
        </template>
      </el-table-column>



      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link :disabled="props.isDisabled">—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>

</template>
<script setup lang="ts">
import { Rdrecord01Api } from '@/api/wms/rdrecord01'
import { InventoryVO, InventoryApi } from '@/api/wms/inventory';
import InventoryForm from './Rdrecords01InventoryForm.vue';
import InventoryForm2 from './Rdrecords01InventoryForm2.vue';

import { PomainApi, PomainsVO } from '@/api/wms/pomain';
import { ElMessage } from 'element-plus';
import { LocationApi, LocationVO } from '@/api/wms/location'

const props = defineProps<{
  pid: number | undefined  // 主表ID（主表的关联字段）
  isDisabled: boolean | undefined // 是否禁用表单      
  pomainId: number | undefined  // 主表ID（主表的关联字段）

}>()
const pomainsList = ref([] as PomainsVO[]);
const locationList = ref([] as LocationVO[]);

const formLoading = ref(false) // 表单的加载中
const selectLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  required: [{ required: true, message: '不能为空', trigger: 'blur' }],

})
const formRef = ref() // 表单 Ref


/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.pid,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      const initialData  = await Rdrecord01Api.getRdrecords01ListByPid(val)
      formData.value = await Promise.all(initialData.map(async (item) => {
        if (item.pomainsId) {
          const inventory = await PomainApi.getPomainsById(item.pomainsId);
          const locationData = await LocationApi.getLocation(item.cposcode)

          return {
            ...item,
            inventoryName: inventory.inventoryName,
            inventoryCode: inventory.inventoryCode,
            inventoryUnitName: inventory.inventoryUnitName,
            inventorySpecModel: inventory.inventorySpecModel,
            cposcode: locationData.id,
            locationName: locationData.name,
            sid:inventory.pid,
            sumQty:inventory.qty,
            useQty:inventory.useQty-item.qty,
          };
         
        }
      
        return item;
      
      }));

    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 查询存货 */
// const remoteInventory = async () => {
//   if(props.pomainId==undefined)
//   {
//     ElMessage.warning(`请先选择采购订单`);
//   }else{
//     pomainsList.value =await PomainApi.getPomainsOperateList(props.pomainId);
//   }
// }

/** 查询货位 */
const remoteLocation = async () => {
  locationList.value =await LocationApi.getLocationSimpleList();
}

/** 处理货位选择变化 */
const handleLocationChange = (value, row) => {
  const selectedInventory = locationList.value.find(item => item.id === value);
  if (selectedInventory) {
    row.cposcode = selectedInventory.id;
    row.locationName = selectedInventory.name;
  }
};


/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    pid: undefined,
    sid: undefined,
    cinvcode: undefined,
    cbatch: undefined,
    cposcode: undefined,
    qty: undefined,
    irate: undefined,
    price: undefined,
    itaxprice: undefined,
    imoney: undefined,
    itax: undefined,
    isum: undefined,
    cbmemo: undefined,
  }
  row.pid = props.pid
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}




//批量新增代码

const formRefAdd = ref(null); // 确保变量名唯一
const formRefAdd2 = ref(null); // 确保变量名唯一

const openDialog = () => {
  if(props.pomainId==undefined)
  {
    ElMessage.warning(`请先选择采购订单`);
  }else{
  // 打开弹窗的逻辑
    formRefAdd.value.open(); // 假设子组件有一个 open 方法
  }
};

const selectedRowIndex = ref(-1); // 用于存储被点击行的索引
const openDialog2 = (index) => {
  if(props.pomainId==undefined)
  {
    ElMessage.warning(`请先选择采购订单`);
  }else{
    selectedRowIndex.value = index;
    // 打开弹窗的逻辑
    formRefAdd2.value.open(event);
    // formRefAdd.value.open(); // 假设子组件有一个 open 方法
  }
};


const handleSuccess = (formData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', formData)
  // 可以在这里调用 API 获取数据等
  const inventoryCodes = formData.inventoryCode;
  console.log('Selected inventory codes:', inventoryCodes);
  // 调用确认选择的方法
  confirmSelection(inventoryCodes);
};

const handleSuccess2 = (getFormData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', getFormData)
  // 可以在这里调用 API 获取数据等
  // 调用确认选择的方法
  // confirmSelection2(inventoryCodes);
  console.log('selectedRowIndex.value:', selectedRowIndex.value)

  if (selectedRowIndex.value !== -1) {
    console.log(formData.value[selectedRowIndex.value])
    formData.value[selectedRowIndex.value] = { ...getFormData.value, ...getFormData };
  }
};


/** 确认选择的存货编码 */
const confirmSelection = async (inventoryCodes: any[]) => {
  try {
    formLoading.value = true;
    const selectedInventoriesData = await Promise.all(inventoryCodes.map(async (id) => {
      const inventory = await PomainApi.getPomainsById(id);
      return {
        id: undefined,
        pid: props.pid,
        pomainsId: id,
        inventoryName: inventory.inventoryName,
        inventoryCode: inventory.inventoryCode,
        inventoryUnitName: inventory.inventoryUnitName,
        inventorySpecModel: inventory.inventorySpecModel,
        qty: undefined,
        irate: inventory.irate,
        price: inventory.price,
        itaxprice: inventory.itaxprice,
        imoney: undefined,
        itax: inventory.itax,
        isum: undefined,
        cbmemo: undefined,
        sid:inventory.pid,
        sumQty:inventory.qty,
        useQty:inventory.useQty,
      };
    }));
    formData.value.push(...selectedInventoriesData);
  } finally {
    formLoading.value = false;
    selectedInventories.value = []; // 重置选中的存货编码
  }
};


const calculateValues = (index: number) => {
  const row = formData.value[index];
  if (row.qty) {
    const itaxprice = parseFloat(row.itaxprice.toString());
    const qty = parseFloat(row.qty.toString());
    const price = parseFloat(row.price.toString());

    const maxQty = row.sumQty - row.useQty;

    if (qty > maxQty) {
      ElMessage.warning(`数量不能超过 ${maxQty}`);
      row.qty = maxQty;
    }

    // 计算金额
    const imoney = itaxprice * qty;
    row.imoney = imoney.toFixed(2);

    // 计算税额
    const itax = imoney - (price * qty);
    row.itax = itax.toFixed(2);

    // 计算价税合计
    const isum = imoney;
    row.isum = isum.toFixed(2);
  }
};

defineExpose({ validate, getData })

</script>